<template>
    <div class="container">
        <el-row :gutter="20">
            <el-col :span="9">
                <p>选择<strong><mark>{{selectNum}}</mark></strong>个样本，寻找同其相似的样本</p>
                <el-form-item label="" prop="transfer">
                    <el-transfer v-model="form.transfer" :data="transferData" :titles="['已上传样本', '选中样本']" filterable/>
                </el-form-item>
                <el-button class="step-btn" type="primary"  @click="similarityMeasure">寻找相似样本</el-button>
            </el-col>

            <el-col :span="15">
                <div class="step-div" v-if = "drawer">
                    <el-collapse v-model="activeName" accordion>
                        <el-collapse-item v-for="(item, index) in items"  :key="index" :title="item.dynamicTitle" :name="index">
                            <p>相似值:
                                <countup class="countup" :end="item.simScore" :options="options" />
                            </p>
                            <el-space wrap>
                                <el-card style="width: 250px">
                                    <template #header>
                                        <div class="card-header">
                                            <span>基本信息对比</span>
                                        </div>
                                    </template>
                                    <p>家族对比：{{item.famLabel1 }} : {{item.famLabel2 }}</p>
                                    <p>图节点: {{item.funcSize1}}:{{item.funcSize2 }}</p>
                                    <p>图边: {{ item.edgeSize1 }}:{{ item.edgeSize2 }}</p>
                                    <p>重复函数 : {{item.reuseFunction }}个</p>

                                </el-card>
                                <el-card style="width: 250px">
                                    <template #header>
                                        <div class="card-header">
                                            <span>灰度图：</span>
                                        </div>
                                    </template> 
                                    <p>
                                        <img :src="item.greyImage1"
                                            style="width: 45%" />
                                        <el-divider direction="vertical" />
                                        <img :src="item.greyImage2"
                                            style="width: 45%" />
                                    </p>
                                </el-card>
                            </el-space>

                        </el-collapse-item>
                    </el-collapse>
                </div>
            </el-col>

        </el-row>

    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, compile } from 'vue';
import axios from 'axios';
import { ElStep } from 'element-plus';

const drawer = ref(false)
const selectNum = ref(1)
const transferData = ref([])
const simScore = ref([])
const dynamicTitle = ref([])

const greyImage1 = ref([])
const greyImage2 = ref([])

const famLabel1 = ref([])
const famLabel2 = ref([])
const reuseFunction = ref([])
const funcSize1 = ref([])
const funcSize2 = ref([])
const edgeSize1 = ref([])
const edgeSize2 = ref([])

const items = ref(famLabel1.value.map((_, index) => ({
      dynamicTitle: `对比项 ${index + 1}`,
      famLabel1: famLabel1.value[index],
      famLabel2: famLabel2.value[index],
      reuseFunction: reuseFunction.value[index],
      funcSize1: funcSize1.value[index],
      funcSize2: funcSize2.value[index],
      edgeSize1: edgeSize1.value[index],
      edgeSize2: edgeSize2.value[index],
      greyImage1: greyImage1.value[index],
      greyImage2: greyImage2.value[index],
      simScore: simScore.value[index]
    })))

const similarityMeasure = async () => {
    try {
        let sampleId1
        let size  = form.transfer.length;
        if(size == 1){
            sampleId1 = transferData.value[form.transfer[0]-1].label
            drawer.value = true
            let userId = 1234
            const response = await axios.post('http://127.0.0.1:5000/calculateSampleSimTopK', { userId,sampleId1 });  // 请求后端数据
            // process data
            // 清空之前的值
            simScore.value = [];
            famLabel1.value = [];
            famLabel2.value = [];
            reuseFunction.value = [];
            funcSize1.value = [];
            edgeSize1.value = [];
            funcSize2.value = [];
            edgeSize2.value = [];
            items.value = []; // 初始化 items 数组
            let imageRequests = [];

            console.log("---")
            console.log(response["data"]["simScore"])
            console.log(response["data"]["basicInfs"])
            for(let i=0;i<response["data"]["simScore"].length;i++){
                simScore.value.push(response["data"]["simScore"][i])
                let tarBasicInf = response["data"]["basicInfs"][i]
                console.log(tarBasicInf)
                famLabel1.value.push(tarBasicInf["famLabel1"])
                famLabel2.value.push(tarBasicInf["famLabel2"])
                reuseFunction.value.push(tarBasicInf["reuseFunction"])
                funcSize1.value.push(tarBasicInf["sampleX"]["funcSize"])
                edgeSize1.value.push(tarBasicInf["sampleX"]["edgeSize"])
                funcSize2.value.push(tarBasicInf["sampleY"]["funcSize"])
                edgeSize2.value.push(tarBasicInf["sampleY"]["edgeSize"])

                // 向图片请求数组添加异步请求
                let imageRequest = axios.post('http://127.0.0.1:5000/queryGreyImage', { tarId: sampleId1 }, { responseType: 'blob' })
                    .then(response => {
                        // 创建一个图片的URL对象
                        let imageUrl = URL.createObjectURL(response.data);
                        greyImage1.value.push(imageUrl);
                        greyImage2.value.push(imageUrl); // 你可以根据需要修改 greyImage2 的值
                    })
                    .catch(error => {
                        console.error('Error fetching image:', error);
                    });

                // 将请求推入数组
                imageRequests.push(imageRequest);
            }
            
            Promise.all(imageRequests).then(() => {
                // 所有异步请求完成后，推送数据到 items 数组
                for (let i = 0; i < response["data"]["simScore"].length; i++) {
                    items.value.push({
                        dynamicTitle: "相似样本: " + i,
                        famLabel1: famLabel1.value[i],
                        famLabel2: famLabel2.value[i],
                        reuseFunction: reuseFunction.value[i],
                        funcSize1: funcSize1.value[i],
                        edgeSize1: edgeSize1.value[i],
                        funcSize2: funcSize2.value[i],
                        edgeSize2: edgeSize2.value[i],
                        simScore: simScore.value[i],
                        greyImage1: greyImage1.value[i],
                        greyImage2: greyImage2.value[i]
                    });
                    }
            })
            console.log(items.value)
        }
        else{
            alert("样本数量选择错误")
        }
    } catch (error) {
        console.error('获取数据失败:', error);
    }
};

const form = reactive({
    name: '',
    region: '',
    date: '',
    time: '',
    delivery: true,
    type: ['小明'],
    resource: '小红',
    desc: '',
    options: [],
    color: '',
    num: 1,
    rate: 0,
    transfer: [],

});

const options = {
    startVal: 0,
    decimalPlaces: 2,
    duration: 5,
    useGrouping: false,
    // prefix: '$',
    separator: ',',
    decimal: '.',
    suffix: '',
}

const activeName = ref('1')

const fetchTableData = async () => {
    try {
        let userId = 1234;
        const response = await axios.post('http://127.0.0.1:5000/querySampleInfoListByUser', { userId });  // 请求后端数据
        transferData.value = []
        var res = []
        for(let ind in response["data"]){
            var tempData = response["data"][ind]
            var dic = new Array()
            console.log(tempData)
            dic["key"] =  tempData[0]
            dic["label"] =  tempData[5]
            transferData.value.push(dic);
        }
    } catch (error) {
        console.error('获取数据失败:', error);
    }
};

const handleRadioChange = (value) => {
    if (value === "selectTopK") {
        selectNum.value = 1;  
    } else if (value === "pairSim") {
        selectNum.value = 2;  
    }
}
// 组件挂载时获取数据
onMounted(() => {
  fetchTableData()
})

</script>

<style scoped>
.step-div {
    max-width: 60%;
    margin: 0 auto;
}

.logo{
    width: 250px;
}
.step-div p {
    margin-bottom: 20px;
    color: #787878;
}

.step-btn {
    display: block;
    width: 100%;
    margin: 20px 0;
}

.step-style {
    max-width: 800px;
    margin: 40px auto;
}
</style>